<?php
include '../../../wp-load.php';
?>
<?php
if ($_FILES) {
  foreach ($_FILES as $file => $array) {
    // New upload contains the attachment_id just uploaded
    $new_upload = insert_attachment($file,null);
  }
}
?>
<?php
function insert_attachment($file_handler,$post_id,$setthumb='false') {
  // NOTICE: this function handles thumbs too, at now they are disabled (TO CHECK)
  // Check to make sure whether it is a successful upload
  if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');
  // Handling compound files (.zip) and other ones
  require_once(ABSPATH . "wp-admin" . '/includes/misc.php');
  $attach_id = media_handle_upload( $file_handler, $post_id );
  if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
  return $attach_id;
}	
?>
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
	if(is_wp_error($new_upload)) {
		//$error_string = $new_upload->get_error_message();
		//echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
		$isValid = false;
	} else {
		// Retrieve download link by attachment_id (NOTICE: it returns an HTML hyperlink)
		$download_link = wp_get_attachment_url($new_upload);
	}
	// Do some minor form validation
	$title = $_POST['title'];
	$description = $_POST['description'];
	$isValid = true;
	$missing_file = "";
	$missing_title = "";
	$missing_description = "";
	if (empty($download_link)) {		
		$isValid = false;
		$missing_file  = true;
	} 
	if (empty($title)) {
		$isValid = false;
		$missing_title = true;
	} 
	if (empty($description)) {		
		$isValid = false;
		$missing_description = true;
	} 
	if ($isValid) {
		// Add the content of the form to $post as an array
		$my_post = array(
			'post_title'	=> $title,
			'post_content'	=> $description,
			'post_status'	=> 'publish',			 // Choose: publish, preview, future, etc.
			'post_type'		=> 	$_POST['post_type']  // Use a custom post type if you want to
		);	
		$postid = wp_insert_post($my_post, true);  // Pass  the value of $my_post to WordPress the insert function
											       // http://codex.wordpress.org/Function_Reference/wp_insert_post
		// Add download link as a new metadata to the post. This is to be retrieved later
		add_post_meta($postid, 'Download Link', $download_link, true);
		// Do the wp_insert_post action to insert it
		do_action('wp_insert_post', 'wp_insert_post'); 
		wp_redirect($_SERVER["HTTP_REFERER"]);
	} else {
		//TODO: HARDCODED PATH?
		wp_redirect('http://localhost/wordpress/wp-content/themes/stardust/error.php' . '?' . 'missing-file=' . $missing_file . '&' . 'missing-title=' . $missing_title . '&' . 'missing-description=' . $missing_description);
	}
} // end IF
?>